//
//  KiwipenEvent.m
//  BlueToothDemo
//
//  Created by US bike on 2017/8/29.
//  Copyright © 2017年 奇异果. All rights reserved.
//

#import "KiwipenEvent.h"
#import "KiwipenProtocol.h"
#import "ToolMethods.h"

@implementation KiwipenEvent

//工厂模式
//封装这个方法可以同时创建对象又调用了下面的方法，因为这个对象只有调用了这个方法才有意义
//instancetype的意思是调用方法地方的返回值要跟封装这个方法类的类型一样
+ (instancetype) CreateEventWithData:(NSData *) data {
    KiwipenEvent *event = [KiwipenEvent new];
    [event setupEventWithData:data];
    return event;
}

+ (instancetype) CreateEventWithType:(EventType) type AndData:(NSData *) data {
    KiwipenEvent *event = [KiwipenEvent new];
    event->_eventType = type;
    event->_eventData = data;
    return event;
}


//判断并组装事件
- (void) setupEventWithData:(NSData *) data {
    Byte* bytes = (Byte *) data.bytes;
    
    if ([data length] < 5) {
        NSLog(@"要组装为事件的data长度小于5个字节，无效。");
        _eventType = EventTypeError;
        return;
    }
    if (bytes[0] != CMD_Begin1 || bytes[1] != CMD_Begin2) {
        NSLog(@"要组装为事件的data起始码不匹配，无效");
        _eventType = EventTypeError;
        return;
    }
    if (bytes[data.length - 1] != CMD_END) {
        NSLog(@"要组装为事件的data结束码不匹配，无效");
        _eventType = EventTypeError;
        return;
    }
    
    Byte operator = bytes[2];
    Byte crc;
    
    //根据识别符判断命令类型
    if (operator == CMD_OPERATOR_BUTTON) {
        _eventType = EventTypeButton;
        NSLog(@"设备按键命令，App收到的数据");
        crc = bytes[5];
        if (crc != [ToolMethods xorsBytes:bytes[2],bytes[3],bytes[4], nil]) {
            _eventType = EventTypeError;
            return;
        }
        if (bytes[3] == BUTTON_UP) {
            if (bytes[4] == BUTTON_FALLING_EDGE) {
                _eventDetailType = EventDetailTypeVALUE_UP_BUTTON_FALLING_EDGE;
            } else if (bytes[4] == BUTTON_RISING_EDGE) {
                _eventDetailType = EventDetailTypeVALUE_UP_BUTTON_RISING_EDGE;
            } else if (bytes[4] == BUTTON_SINGLE_CLICK) {
                _eventDetailType = EventDetailTypeVALUE_UP_BUTTON_SINGLE_CLICK;
            } else if (bytes[4] == BUTTON_DOUBLE_CLICK) {
                _eventDetailType = EventDetailTypeVALUE_UP_BUTTON_DOUBLE_CLICK;
            } else if (bytes[4] == BUTTON_LONG_PRESS) {
                _eventDetailType = EventDetailTypeVALUE_UP_BUTTON_LONG_PRESS;
            } else if (bytes[4] == BUTTON_LONG_RELEASE) {
                _eventDetailType = EventDetailTypeVALUE_UP_BUTTON_LONG_RELEASE;
            }
        } else if (bytes[3] == BUTTON_DOWN) {
            if (bytes[4] == BUTTON_FALLING_EDGE) {
                _eventDetailType = EventDetailTypeVALUE_DOWN_BUTTON_FALLING_EDGE;
            } else if (bytes[4] == BUTTON_RISING_EDGE) {
                _eventDetailType = EventDetailTypeVALUE_DOWN_BUTTON_RISING_EDGE;
            } else if (bytes[4] == BUTTON_SINGLE_CLICK) {
                _eventDetailType = EventDetailTypeVALUE_DOWN_BUTTON_SINGLE_CLICK;
            } else if (bytes[4] == BUTTON_DOUBLE_CLICK) {
                _eventDetailType = EventDetailTypeVALUE_DOWN_BUTTON_DOUBLE_CLICK;
            } else if (bytes[4] == BUTTON_LONG_PRESS) {
                _eventDetailType = EventDetailTypeVALUE_DOWN_BUTTON_LONG_PRESS;
            } else if (bytes[4] == BUTTON_LONG_RELEASE) {
                _eventDetailType = EventDetailTypeVALUE_DOWN_BUTTON_LONG_RELEASE;
            }
        } else if (bytes[3] == BUTTON_MID) {
            if (bytes[4] == BUTTON_FALLING_EDGE) {
                _eventDetailType = EventDetailTypeVALUE_MID_BUTTON_FALLING_EDGE;
            } else if (bytes[4] == BUTTON_RISING_EDGE) {
                _eventDetailType = EventDetailTypeVALUE_MID_BUTTON_RISING_EDGE;
            } else if (bytes[4] == BUTTON_SINGLE_CLICK) {
                _eventDetailType = EventDetailTypeVALUE_MID_BUTTON_SINGLE_CLICK;
            } else if (bytes[4] == BUTTON_DOUBLE_CLICK) {
                _eventDetailType = EventDetailTypeVALUE_MID_BUTTON_DOUBLE_CLICK;
            } else if (bytes[4] == BUTTON_LONG_PRESS) {
                _eventDetailType = EventDetailTypeVALUE_MID_BUTTON_LONG_PRESS;
            } else if (bytes[4] == BUTTON_LONG_RELEASE) {
                _eventDetailType = EventDetailTypeVALUE_MID_BUTTON_LONG_RELEASE;
            }
        }
    } else if (operator == CMD_OPERATOR_POWER) {
        crc = bytes[5];
        if (crc != [ToolMethods xorsBytes:bytes[2],bytes[3],bytes[4], nil]) {
            _eventType = EventTypeError;
            return;
        }
        NSLog(@"电池电量命令");
        _eventType = EventTypePower;
        _eventData = [data subdataWithRange:NSMakeRange(3, 2)];
    } else if (operator == CMD_OPERATOR_LED) {
        NSLog(@"这里是LED命令， 不属于事件，这里不处理");
        _eventType = EventTypeError;
        return;
    } else if (operator == CMD_OPERATOR_UUID) {
        int uuidLength = 0xFF & bytes[3];
        Byte uuidCRC = bytes[4];
        for (int i = 1; i < uuidLength; i++) {
            uuidCRC = [ToolMethods xorByteA:uuidCRC AndByteB:bytes[i + 4]];
        }
        crc = bytes[4 + uuidLength];
        if (crc != [ToolMethods xorsBytes:bytes[2], bytes[3], uuidCRC, nil]) {
            _eventType = EventTypeError;
            return;
        }
        NSLog(@"读取UUID命令，App发送读请求");
        if (data.length == 5) {
            NSLog(@"APP发送读取UUID命令");
        } else {
            NSLog(@"APP接收读取UUDI的数据");
        }
        //设置数据
        _eventType = EventTypeUUID;
        _eventData = [data subdataWithRange:NSMakeRange(4, uuidLength)];
    }
}

//还不知道是干什么用的
- (NSString *) description {
    return [NSString stringWithFormat:@"kiwipenEvent  type = %lu, detailType = %lu, eventData = %@", (unsigned long)self.eventType,(unsigned long)self.eventDetailType,self.eventData];
}

//根据收到的不同按键事件，分别发送各自的通知中心
- (void)doMethodsJudgingByEventTypeAndEventDetailTypeOfKiwipenEvent {
    //上升沿和下降沿可以不用理会
    //按钮，上键
    if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_UP_BUTTON_FALLING_EDGE) {
        NSLog(@"收到事件--按键消息--上键下降沿");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonUpFallingEdgeNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_UP_BUTTON_RISING_EDGE) {
        NSLog(@"收到事件--按键消息--上键上升沿");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonUpRisingEdgeNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_UP_BUTTON_SINGLE_CLICK) {
        NSLog(@"收到事件--按键消息--上键单击");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonUpSingleClickNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_UP_BUTTON_DOUBLE_CLICK) {
        NSLog(@"收到事件--按键消息--上键双击");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonUpDoubleClickNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_UP_BUTTON_LONG_PRESS) {
        NSLog(@"收到事件--按键消息--上键长按");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonUpLongPressNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_UP_BUTTON_LONG_RELEASE) {
        NSLog(@"收到事件--按键消息--上键长按释放");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonUpLongReleaseNoti object:nil];
    }
    //按钮，下键
    else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_DOWN_BUTTON_FALLING_EDGE) {
        NSLog(@"收到事件--按键消息--下键下降沿");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonMidLongPressNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_DOWN_BUTTON_RISING_EDGE) {
        NSLog(@"收到事件--按键消息--下键上升沿");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonDownRisingEdgeNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_DOWN_BUTTON_SINGLE_CLICK) {
        NSLog(@"收到事件--按键消息--下键单击");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonDownSingleClickNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_DOWN_BUTTON_DOUBLE_CLICK) {
        NSLog(@"收到事件--按键消息--下键双击");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonDownDoubleClickNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_DOWN_BUTTON_LONG_PRESS) {
        NSLog(@"收到事件--按键消息--下键长按");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonDownLongPressNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_DOWN_BUTTON_LONG_RELEASE) {
        NSLog(@"收到事件--按键消息--下键长按释放");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonDownLongReleaseNoti object:nil];
    }
    //按钮，中键
    else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_MID_BUTTON_FALLING_EDGE) {
        NSLog(@"收到事件--按键消息--中键下降沿");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonMidFallingEdgeNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_MID_BUTTON_RISING_EDGE) {
        NSLog(@"收到事件--按键消息--中键上升沿");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonMidRisingEdgeNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_MID_BUTTON_SINGLE_CLICK) {
        NSLog(@"收到事件--按键消息--中键单击");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonMidSingleClickNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_MID_BUTTON_DOUBLE_CLICK) {
        NSLog(@"收到事件--按键消息--中键双击");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonMidDoubleClickNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_MID_BUTTON_LONG_PRESS) {
        NSLog(@"收到事件--按键消息--中键长按");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonMidLongPressNoti object:nil];
    }else if (self.eventType == EventTypeButton && self.eventDetailType == EventDetailTypeVALUE_MID_BUTTON_LONG_RELEASE) {
        NSLog(@"收到事件--按键消息--中键长按释放");
        [[NSNotificationCenter defaultCenter] postNotificationName:ButtonMidLongReleaseNoti object:nil];
    }
    //其他事件
    else if (self.eventType == EventTypeError) {
        NSLog(@"收到事件--无效指令");
        [[NSNotificationCenter defaultCenter] postNotificationName:ErrorNotification object:nil];
    }else if (self.eventType == EventTypePower) {
        NSLog(@"收到事件--电量消息");
        NSString *str = [self transformPowerDataToStringWithData:self.eventData];
        [[NSNotificationCenter defaultCenter] postNotificationName:PowerNotification object:str];
 
        
    }else if (self.eventType == EventTypeUUID) {
        NSLog(@"收到事件--收到deviceId数据");

        //要从这里获取UUID下的deviceid数据
        NSString *str = [self transformUUIDDataToStringWithData:self.eventData];
        [[NSNotificationCenter defaultCenter] postNotificationName:UUIDNotification object:str];
 
    } else if (self.eventType == EventTypeBLEConnected) {
        NSLog(@"收到事件--蓝牙连接成功");
        NSString *uuidStr = [[NSString alloc] initWithData:self.eventData encoding:NSUTF8StringEncoding];

        
        [[NSNotificationCenter defaultCenter] postNotificationName:BLEConnectedNotification object:uuidStr];

        
    } else if (self.eventType == EventTypeBLEDisConnected) {
        NSLog(@"收到事件--蓝牙连接断开");
        [[NSNotificationCenter defaultCenter] postNotificationName:BLEDisconnectedNotification object:nil];
    }
}

//接收到电量事件后调用，将。。。
- (NSString *) transformPowerDataToStringWithData:(NSData *) data {
    Byte *bytes = (Byte *)data.bytes;
    
    if (data.length != 2) {
        NSLog(@"电池电量数据不正确");
        return @"获取失败";
    }
    
    NSInteger electricity = (bytes[0] << 8) + bytes[1];
    
    NSMutableArray *electricityArray = [NSMutableArray arrayWithArray
                                :@[@(3047),@(3208),@(3309),@(3378),@(3427),@(3469),@(3501),@(3522),@(3540),@(3554),@(3565),@(3574),@(3580),@(3585),@(3592),@(3599),@(3605),@(3610),@(3615),@(3621),@(3625),@(3629),@(3633),@(3637),@(3640),@(3644),@(3647),@(3650),@(3653),@(3655),@(3657),@(3659),@(3662),@(3663),@(3665),@(3667),@(3669),@(3671),@(3673),@(3676),@(3678),@(3680),@(3683),@(3686),@(3689),@(3692),@(3694),@(3698),@(3702),@(3705),@(3708),@(3713),@(3716),@(3720),@(3724),@(3729),@(3734),@(3738),@(3743),@(3749),@(3755),@(3760),@(3765),@(3771),@(3778),@(3784),@(3789),@(3796),@(3802),@(3808),@(3814),@(3822),@(3828),@(3834),@(3840),@(3847),@(3854),@(3859),@(3866),@(3872),@(3878),@(3884),@(3892),@(3901),@(3911),@(3922),@(3933),@(3944),@(3953),@(3960),@(3967),@(3976),@(3985),@(3995),@(4005),@(4017),@(4029),@(4042),@(4058),@(4088)]];
    
    NSString *percent = @"--";
    for (int i = 0; i < electricityArray.count; i++) {
        if (electricity <= [electricityArray[i] integerValue]) {
            //i + 1;
            percent = [NSString stringWithFormat:@"%ld%%",(long)(i+1)];
            NSLog(@"电量百分比是百分之%ld",(long)(i + 1));
            break;
        }
    }
    return percent;
}

- (NSString *) transformUUIDDataToStringWithData:(NSData *) data {
    
    NSString *temp = data.description;
    
    temp = [temp stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"<" withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@">" withString:@""];
    temp = [temp uppercaseString];
    
    return temp;
}

@end
